from fastapi.middleware.cors import CORSMiddleware
from fastapi import FastAPI
from fastapi import FastAPI, APIRouter
from fastapi.staticfiles import StaticFiles
from fastapi import FastAPI, UploadFile, Request, Depends, Form
from fastapi.responses import FileResponse
from pathlib import Path
from tortoise.contrib.fastapi import register_tortoise
from starlette.responses import RedirectResponse
from models import Form_1_Data
import json
import os
from fastapi.responses import StreamingResponse
from pathlib import Path


app = FastAPI()

register_tortoise(
    app,
    db_url="sqlite://database.db",
    # db_url="sqlite://:memory:",
    modules={"models": ["models"]},
    generate_schemas=True,
)

# 添加跨域中间件
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

@app.put("/UpdateFile")
async def _(file: UploadFile):
	# 保存文件到指定目录
    file_path = os.path.join("D:/FromFilesDB/", file.filename)
    with open(file_path, "wb") as buffer:
        buffer.write(await file.read())

@app.get("/DownloadFile")
async def _(fileName:str=""):    
    output_path = Path("D:/FromFilesDB/" + fileName + ".pdf")
    # return FileResponse(output_path, filename=fileName+".pdf")
    # 打开文件并流式传输内容
    file_stream = open(output_path, mode="rb")
    return StreamingResponse(file_stream, media_type="application/pdf")
